<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="com.emip.bean.UserBean"%>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<style type="text/css">
    html,body{margin:0;padding:0;}
    .iw_poi_title {color:#CC5522;font-size:14px;font-weight:bold;overflow:hidden;padding-right:13px;white-space:nowrap}
    .iw_poi_content {font:12px arial,sans-serif;overflow:visible;padding-top:4px;white-space:-moz-pre-wrap;word-wrap:break-word}
</style>

<style type="text/css">
        #infoTable 
        {
            border:1px solid #cccccc;
			border-collapse: collapse;
			table-layout : fixed;/**/
			width:100%;
        }
        #infoTable th{
			border:1px solid #cccccc;
			text-align:center;
			background-color:#eeeeee;
			padding:10px;
		}
		#infoTable td{
			border:1px solid #cccccc;
			text-align:left;
			padding:10px;
		}

</style>


<html xmlns="http://www.w3.org/1999/xhtml">

	<%@ include file="header.jsp"%>
	<script type="text/javascript"
		src="http://api.map.baidu.com/api?key=&v=1.3&services=true"></script>
	<script type="text/javascript" src="<%=resourceBase%>customJS/map/convertor.js"></script>

	<body>
		<div id="body-wrapper">
			<!-- Wrapper for the radial gradient background -->

			<!-- sidebar.jsp -->
			
			<%@ include file="sidebar.jsp"%> 
			
			
			<div id="searchDiv" align="right">
				<span id="connErrorInfo" style= "text-align:center;display:inline-block;width:40%;margin-right:20%;background-color:#fffd76; ">网络异常，站点坐标无法更新</span>
				<select id="siteList">
				</select>
				<button onclick="goSite()">快速定位</button>
			</div>
			<div id="sitesDituContent">
			</div>
		</div>
	</body>
	<script type="text/javascript">
		//创建和初始化地图函数：
		function initMap() {
			createMap();//创建地图
			setMapEvent();//设置地图事件
			addMapControl();//向地图添加控件
			addMarker();//向地图中添加marker
			//两分钟重置一下位置坐标，2分钟=120000毫秒
			setInterval(addMarker, 120000);
		}

		//创建地图函数：
		//从action处获取当前用户定义的坐标位置
		var curUser;
		$.ajax({
		type: "POST",
		url : getContextPath()+"/user/curUser.do", 
			data : {},
			dataType : "json",
			async : false,
			cache: false,
			error : function(textStatus, errorThrown) {
				alert("系统ajax交互错误: " + textStatus);
			},
			success : function(data, textStatus) {
				if (data != null) {
					curUser = data;
				}
			}
	    });
		function createMap() {
			var map = new BMap.Map("sitesDituContent");//在百度地图容器中创建一个地图
			//var point = new BMap.Point(121.509566, 31.236195);//定义一个中心点坐标
			var avWidth = $("#body-wrapper").width()-250;
			var avHeigth = $(window).height() - 75;
			$('#sitesDituContent').css("width",avWidth).css("height",avHeigth);
			var point = new BMap.Point(curUser.longitude, curUser.latitude);
			
			//map.centerAndZoom(point, 11);//设定地图的中心点和坐标并将地图显示在地图容器中
			map.centerAndZoom(point, curUser.mapZoom);
			window.map = map;//将map变量存储在全局
		}

		//地图事件设置函数：
		function setMapEvent() {
			map.enableDragging();//启用地图拖拽事件，默认启用(可不写)
			map.enableScrollWheelZoom();//启用地图滚轮放大缩小
			map.enableDoubleClickZoom();//启用鼠标双击放大，默认启用(可不写)
			map.enableKeyboard();//启用键盘上下左右键移动地图
		}

		//地图控件添加函数：
		function addMapControl() {
			//向地图中添加缩放控件
			var ctrl_nav = new BMap.NavigationControl( {
				anchor : BMAP_ANCHOR_TOP_LEFT,
				type : BMAP_NAVIGATION_CONTROL_LARGE
			});
			map.addControl(ctrl_nav);
			//向地图中添加缩略图控件
			var ctrl_ove = new BMap.OverviewMapControl( {
				anchor : BMAP_ANCHOR_BOTTOM_RIGHT,
				isOpen : 1
			});
			map.addControl(ctrl_ove);
			//向地图中添加比例尺控件
			var ctrl_sca = new BMap.ScaleControl( {
				anchor : BMAP_ANCHOR_BOTTOM_LEFT
			});
			map.addControl(ctrl_sca);
		}

		//标注点数组
		/**
		var markerArr = [ {name : "南码头", mTypeName : "水监测", areaName : "上海市", valley : "长江水系", waterSystem : "长江",
							alongSide : "九江", qualityLevel : "III", gps : "121.535617|31.252619"},
					  {name : "外高桥", mTypeName : "大气监测", areaName : "上海市", valley : "长江水系", waterSystem : "东海",
							alongSide : "黄浦江", qualityLevel : "IV", gps : "121.638527|31.341979"},
					  {name : "淀山湖", mTypeName : "污染源监测", areaName : "上海市", valley : "太湖水系", waterSystem : "淀山湖",
							alongSide : "青浦", qualityLevel : "劣IV", gps : "121.016181|31.152297"}		
					];
					**/
		//申明site列表数组
		var markerArr = new Array();
		//申明siteList列表控件
		var siteListSelect = $("#siteList");
		
		//通用的isOpen
		var isOpen = 0;
		//通用的icon
		var icon = {w : 21,h : 21,l : 0,t : 0,x : 6,lb : 5};
		//var icon = {w : 42,h : 42,l : 0,t : 0,x : 6,lb : 5};
	
		//marker列表
		var markerList = new Array();
		//创建marker
		function addMarker() {
			//从服务器得到site列表
			$.ajax({
				type: "POST",
				//url : getContextPath()+"/site/site/getAllSitesObj.do",
				url : getContextPath()+"/user/getCurrentUserSites.do",
				data : {},
				dataType : "json",
				async : false,
				cache: false,
				error : function(textStatus, errorThrown) {
					//alert("系统ajax交互错误: " + textStatus);
					if ($("#connErrorInfo")[0].style.display == "none") {
						$("#connErrorInfo")[0].style.display = "inline-block";
					}
				},
				success : function(data, textStatus) {
					if (data != null) {
						if ($("#connErrorInfo")[0].style.display == "inline-block") {
							$("#connErrorInfo")[0].style.display = "none";
						}
						markerArr = data;
					}
				}
			});
			//重新填充siteList
			siteListSelect.empty();
			for (var i=0; i<markerArr.length; i++) {
				//以下这句在IE8中无效
				//siteListSelect.append(new Option(markerArr[i].id+":"+markerArr[i].name, i));
				siteListSelect.append('<option value="'+i+'">'+markerArr[i].id+":"+markerArr[i].name+'</option>');
			}
		
			for ( var i = 0; i < markerArr.length; i++) {
				var json = markerArr[i];
				//根据gpsFixed判断是使用固定坐标还是最新坐标
				var flag = json.gpsFixed;
				if (flag=='T') {
					var p0 = json.fixtedLongitude;
					var p1 = json.fixtedLatitude;					
				} else {
					//var p0 = json.gpsPoint.split("|")[0];
					//var p0 = json.curLongitude;
					var p0 = parseFloat(json.curLongitude) + json.longitudeSetoff;
					//var p1 = json.gpsPoint.split("|")[1];
					//var p1 = json.curLatitude;
					var p1 = parseFloat(json.curLatitude) + json.latitudeSetoff;
				}
				//在后期刷新中，若当前i站点fixgps是F并且markerList[i]有内容，则删除数组中该内容，删除图中标记
				if ((markerList[i]!=null) && (flag=='F')) {
					map.removeOverlay(markerList[i]);
					markerList[i] = null;
				}
				//若markerList[i]是null（第一次创建，或者后期刷新阶段被null），那么增加marker
				if (markerList[i]==null) {
					var point = new BMap.Point(p0, p1);
					//谷歌坐标转换为百度坐标，调用回调函数
					BMap.Convertor.translate(point,0,i,translateCallback);
				}
			}
		};
		
		var translateCallback = function (index,point) {
					var json = markerArr[index];
					var iconImg = createIcon(icon);
					var marker = new BMap.Marker(point, {
						icon : iconImg
					});
					markerList[index] = marker;
					//var iw = createInfoWindow(index);
					var label = new BMap.Label(json.name, {
						"offset" : new BMap.Size(icon.lb - icon.x + 10, -20)
					});
					marker.setLabel(label);
			
					map.addOverlay(marker);
					label.setStyle( {
						borderColor : "#808080",
						color : "#333",
						cursor : "pointer"
					});
					(function() {
						var index2 = index;
						var _iw = createInfoWindow(index2);
						var _marker = marker;
						_marker.addEventListener("click", function() {
							this.openInfoWindow(_iw);
						});
						_iw.addEventListener("open", function() {
							_marker.getLabel().hide();
						})
						_iw.addEventListener("close", function() {
							_marker.getLabel().show();
						})
						label.addEventListener("click", function() {
							_marker.openInfoWindow(_iw);
						})
						if (!!isOpen) {
							label.hide();
							_marker.openInfoWindow(_iw);
						}
					})()
		};		
	
		function getContextPath() {
    		var pathName = document.location.pathname;
    		var index = pathName.substr(1).indexOf("/");
    		var result = pathName.substr(0,index+1);
    		return result;
		};
	
		//创建InfoWindow
    	function createInfoWindow(i){
       		var json = markerArr[i];
       	 	//var iw = new BMap.InfoWindow("<b class='iw_poi_title' title='" + json.title + "'>" + json.title + "</b><div class='iw_poi_content'>"+json.content+"</div>");
       	 	var html = "<div id=\"infoWindow_"+json.name+"\"><form id=\"infoForm\"><table id=\"infoTable\"><tr><th>检测类别:</th><td>"+json.monitorType.name+"</td><th>站点区域:</th><td>"+json.area.city+"</td></tr>";
       	 	html += "<tr><th>流域:</th><td>"+json.valley.name+"</td><th>水系:</th><td>"+json.valley.waterSystem+"</td></tr>";
     	 	html += "<tr><th>断面:</th><td>"+json.valley.alongSide+"</td><th>评测标准:</th><td>"+json.qualityName+"</td></tr></table></form>"
       	 	html += "<button class=\"right-button02\" onclick=\"javascript:location.href='"+getContextPath()+"/site/site/detail.do?siteid="+json.id+"'\">查看详细</button></div></div>";
       	 	var iw = new BMap.InfoWindow(html, {width:350, height:150, title:"站点名称: "+json.name});  
       	 	return iw;
    	}
	
		//创建一个Icon
    	function createIcon(json){
        	var icon = new BMap.Icon("http://map.baidu.com/image/us_cursor.gif", new BMap.Size(json.w,json.h),{imageOffset: new BMap.Size(-json.l,-json.t),infoWindowOffset:new BMap.Size(json.lb+5,1),offset:new BMap.Size(json.x,json.h)});
        	return icon;
    	}
    
		initMap();//创建和初始化地图

		function goSite() {
			var siteName = $("#siteList").val();
			var maker = markerList[siteName];
			var _iw = createInfoWindow(siteName);
			maker.openInfoWindow(_iw);
		}
</script>

</html>
